package com.example.rfid_client_volunteer.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClientHelper {

    public String startClientByIDAndIp(String id,String ip) throws IOException {
                int port = 55555;
                Socket socket = new Socket(ip,port);
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(("requestuserinfo:"+ id).getBytes("UTF-8"));
                socket.shutdownOutput();
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len;
                StringBuilder sb = new StringBuilder();
                while ((len = inputStream.read(bytes)) != -1) {
                    //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                    sb.append(new String(bytes, 0, len,"UTF-8"));
                }
                outputStream.close();
                inputStream.close();
                socket.close();
        System.out.println("SB:"+sb.toString());
                return  sb.toString();
    }


    /*@Param1,ip addr
    *@Param2,user id
    *@Param3,client message
    * */
    public void writeToServer(String ip,String id,String msg) throws Exception {
        int port = 55555;
        Socket socket = new Socket(ip,port);
        OutputStream outputStream = socket.getOutputStream();
        System.out.printf("%s,%s,%s",ip,id,msg);
        outputStream.write(("requestuserupdate:"+ id+":"+msg).getBytes("UTF-8"));
        outputStream.close();
    }


}
